﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenSoftStore.BusinessLogic.Product;
using OpenSoftStore.BusinessLogic.Admin;
using OpenSoftStore.BusinessLogic.Common;
using OpenSoftStore.Client.Common;
using OpenSoftStore.Orm.View;
using OpenSoftStore.Orm.Model;

namespace OpenSoftStore.Client.UIL.ManageProduct
{
    public partial class ProductInput : UserControl
    {
        private const string _ShopId = "b0def1a7-bf25-45f2-b65a-6dc586dbfc2c";

        private T_StoreIO storeIO;
        private T_StoreIOItem storeItem;
        private ProductLogic productBll;
        private AdminLogic adminBll;
        private ComboLogic comboBll;
        private List<V_StoreIOItem> storeItems;
        private static ProductInput instance;
        public Boolean Drog = false;
        public int Top = 0;
        public int Left = 0;

        public static ProductInput Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ProductInput();
                }
                return instance;
            }
        }

        public ProductInput()
        {
            productBll = new ProductLogic();
            adminBll = new AdminLogic();
            comboBll = new ComboLogic();
            storeItems = new List<V_StoreIOItem>();
            storeIO = new T_StoreIO();
            storeItem = new T_StoreIOItem();
            InitializeComponent();
            LoadControlData();
            txtProductSearch.Focus();
            SPACommon.SetDataGridStyle(dgvProduct);
            SPACommon.SetDataGridStyle(dgvProductInput);
        }

        private void LoadControlData()
        {
            txtProductSearch.Focus();
            cmbProvider.ValueMember = "Id";
            cmbProvider.DisplayMember = "Name";
            cmbProvider.DataSource = productBll.GetProvider();

            cmbAdmin.ValueMember = "Id";
            cmbAdmin.DisplayMember = "Name";
            cmbAdmin.DataSource = adminBll.GetAdminList();


            colPos.DisplayMember = "DisplayText";
            colPos.ValueMember = "Value1";

            var posItems = comboBll.GetComboByBuzType("Pos", _ShopId).ToList();
            colPos.DataSource = posItems;

            txtOrder.Text = productBll.GetCountNo("T_StoreIO", true);

            dgvProductInput.AutoGenerateColumns = false;
            dgvProduct.AutoGenerateColumns = false;
            dgvProduct.DataSource = productBll.GetProductList();
            lblProductCount.Text = dgvProduct.RowCount.ToString();
            dgvProductInput.DefaultCellStyle.NullValue = posItems[0].DisplayText;
        }

        public void GetStore(T_StoreIO store)
        {
            storeIO.Id = store.Id;
            switch (store.BuzType)
            {
                case "进货":
                    rbIn.Checked = true;
                    break;
                case "调拨调入":
                    rbTransfer.Checked = true;
                    break;
                case "盘盈":
                    rbInventoryProfit.Checked = true;
                    break;
                default:
                    break;
            }

            txtOrder.Text = store.StroeIONo;
            cmbProvider.SelectedValue = store.BuzUserId;
            cmbAdmin.SelectedValue = store.AdminId;
            dtpInputTime.Value = store.AddTime;
            txtRemark.Text = store.Remark;
            storeItems = productBll.GetStoreItemView(" where S.StoreIOId='" + store.Id + "'").ToList();
            dgvProductInput.DataSource = storeItems;
        }

        private void ProductInput_Load(object sender, EventArgs e)
        {
            txtProductSearch.Focus();
            txtProductSearch.Select();
        }

        private void btnProvider_Click(object sender, EventArgs e)
        {

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //ProductAddWindow productAddWindow = new ProductAddWindow();
            //productAddWindow.ShowDialog();
            //var data = productAddWindow.productAdd.product;
        }

        public void GenerateGridView()
        {
            ComboLogic comboBll = new ComboLogic();
            colPos.DisplayMember = "DisplayText";
            colPos.ValueMember = "Value1";
            colPos.DataSource = comboBll.GetComboByBuzType("Pos", _ShopId);
        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
            if (dgvProduct.Rows.Count == 0)
            {
                FormSysMessage.ShowMessage("目前没有添加一个商品，请添加完商品再入库！");
                return;
            }
            if (dgvProduct.CurrentRow != null)
            {
                string id = dgvProduct.CurrentRow.Cells["productId"].Value.ToString();
                string name = dgvProduct.CurrentRow.Cells["name"].Value.ToString();
                decimal inPrice = Convert.ToDecimal(dgvProduct.CurrentRow.Cells["inPrice"].Value);
                string unit = dgvProduct.CurrentRow.Cells["unit"].Value.ToString();
                decimal subAmount = Convert.ToDecimal(dgvProduct.CurrentRow.Cells["SubAmount"].Value);
                string pos = ((T_Combo)colPos.Items[0]).Value1;
                storeItems.Add(new V_StoreIOItem
                    {
                        ProductId = id,
                        Name = name,
                        Price = inPrice,
                        Amount = 1,
                        Unit = unit,
                        Pos = pos,
                        SubAmount = subAmount
                    });

                dgvProductInput.DataSource = null;
                dgvProductInput.DataSource = storeItems;
                lblCount.Text = dgvProductInput.RowCount.ToString();

            }
        }

        private void btnDeleteItem_Click(object sender, EventArgs e)
        {
            if (dgvProductInput.CurrentRow != null)
            {
                var row = dgvProductInput.SelectedRows[0];
                string id = row.Cells["colId"].Value.ToString();
                var storeItem = storeItems.Where<V_StoreIOItem>(s => s.ProductId == id).FirstOrDefault();
                storeItems.Remove(storeItem);
                dgvProductInput.DataSource = null;
                dgvProductInput.DataSource = storeItems;
                lblCount.Text = dgvProductInput.RowCount.ToString();
            }
        }

        private void SetValue()
        {
            storeIO.StroeIONo = txtOrder.Text;
            storeIO.Remark = txtRemark.Text;
            storeIO.AdminId = cmbAdmin.SelectedValue.ToString();
            storeIO.AddTime = dtpInputTime.Value;
            storeIO.Type = "入库";
            storeIO.ProductKinds = dgvProductInput.Rows.Count;
            storeIO.BuzUserId = cmbProvider.SelectedValue.ToString();
            storeIO.ShopId = _ShopId;
        }

        private void btnSave_Click_1(object sender, EventArgs e)
        {
            if (dgvProductInput.Rows.Count == 0)
            {
                FormSysMessage.ShowMessage("请选择商品！");
                return;
            }

            SetValue();

            if (rbIn.Checked)
            {
                storeIO.BuzType = "进货";
            }
            else if (rbTransfer.Checked)
            {
                storeIO.BuzType = "调拨调入";
            }
            else if (rbInventoryProfit.Checked)
            {
                storeIO.BuzType = "盘盈";
                storeIO.Type = "盘点";
            }

            storeItems = (List<V_StoreIOItem>)dgvProductInput.DataSource;
            if (string.IsNullOrEmpty(storeIO.Id))
            {
                storeIO.Id = Guid.NewGuid().ToString("D");
                productBll.AddStoreIO(storeIO, storeItems, true);
            }
            else
            {
                productBll.UpdateStoreIO(storeIO, storeItems, true);
            }

            this.FindForm().Close();


        }

        private void txtProductSearch_KeyUp(object sender, KeyEventArgs e)
        {
            string whereStr = txtProductSearch.Text;
            if (rbSelect.Checked)
            {
                dgvProduct.DataSource = productBll.GetProductList(string.Format(" where P.Name like '{0}%' or P.ProductNo like '{0}%' or P.Model like '{0}%' or prov.Name like '{0}%' or T.Code like '{0}%'", whereStr));

            }
            else
            {
                dgvProduct.DataSource = productBll.GetProductList(" where E.BarCode='" + whereStr + "'");
            }
            lblProductCount.Text = dgvProduct.RowCount.ToString();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.FindForm().Close();
        }

        private void pbClose_Click(object sender, EventArgs e)
        {
            this.FindForm().Close();
        }

        private void rbInventoryProfit_CheckedChanged(object sender, EventArgs e)
        {
            if (rbInventoryProfit.Checked)
            {
                cmbProvider.Enabled = false;
            }
            else
            {
                cmbProvider.Enabled = true;
            }
        }

        private void txtProductSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (rbBarCode.Checked)
            {
                if (e.KeyCode == Keys.Enter)
                {
                    string whereStr = txtProductSearch.Text;
                    dgvProduct.DataSource = productBll.GetProductList(" where E.BarCode='" + whereStr + "'");
                    lblProductCount.Text = dgvProduct.RowCount.ToString();
                    btnAddItem_Click(null, null);
                }
            }
        }

        private void PnlInfoTitle_MouseDown(object sender, MouseEventArgs e)
        {
            Drog = true;
            Top = e.Y;
            Left = e.X;
        }

        private void PnlInfoTitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (!Drog) return;
            var findForm = FindForm();
            if (findForm == null) return;
            findForm.Top += e.Y - Top;
            findForm.Left += e.X - Left;
        }

        private void PnlInfoTitle_MouseUp(object sender, MouseEventArgs e)
        {
            Drog = false;
        }

    }
}
